﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;
using System.Text;

public partial class Pub_Ajax_AjaxQueryAdmin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        Response.Expires = -1;
        Response.ContentType = "text/plain";
        ProcessPage(Request.QueryString["type"]);
        Response.End();
    }

    private void ProcessPage(string type)
    {
        if (type.ToLower() == "addbasket")
        {
            Response.Write(AddBasket());
        }
        else if (type.ToLower() == "orderappbasket")
        {
            Response.Write(OrderAppBasket());
        }
        else if (type.ToLower() == "loadcataloguebytopic")
        {
            Response.Write(LoadCatalogueByTopic());
        }
        else if (type.ToLower() == "getfloworderhist")
        {
            Response.Write(GetFlowOrderHist());
        }
    }

    #region FlowSignHist
    private string GetFlowOrderHist()
    {
        PccMsg msg = new PccMsg();
        string OrderID = Request.QueryString["OrderID"];
        Table tbl = new Table();
        tbl.CellPadding = 2;
        tbl.CellSpacing = 0;
        tbl.Width = Unit.Percentage(100);
     

        CreateHeader(ref tbl);
        CreateRow(ref tbl);

        return _GetControlRenderString(tbl);


    }
    private void CreateRow(ref Table tbl)
    {

        string OrderID = Request.QueryString["OrderID"];
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"].Trim());
        clsWebShop cls = new clsWebShop();
        DataTable dt = null;
        dt = cls.Get_FlowOrderHistByCondition(msg.GetXmlStr).Tables[0];


        TableRow row;
        TableCell cell;
        msg = new PccMsg();
        msg.CreateFirstNode("Css", "tbl1_trRow");

        if (dt.Rows.Count > 0)
        {

            clsFunAp clsFun = new clsFunAp();
            clsCommon clsCom = new clsCommon();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int index = i + 1;

                row = new TableRow();

                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Center;
                AddCellTextToRow(row, cell, index.ToString(), msg);


                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Center;
                AddCellTextToRow(row, cell, dt.Rows[i]["SignNm"].ToString(), msg);

                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Center;
                AddCellTextToRow(row, cell, clsCom.FormatDateTime(dt.Rows[i]["SignDate"].ToString()), msg);

                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Left;
                AddCellTextToRow(row, cell, dt.Rows[i]["Note"].ToString(), msg);

                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Center;
                AddCellTextToRow(row, cell, clsFun.ReturnStatus(dt.Rows[i]["Status"].ToString()), msg);

                tbl.Rows.Add(row);
            }
        }
        else
        {
            row = new TableRow();
            cell = new TableCell();
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.ColumnSpan = tbl.Rows[tbl.Rows.Count - 1].Cells.Count;
            AddCellTextToRow(row, cell, "Không tìm thấy dữ liệu", msg);
            tbl.Rows.Add(row);

        }


    }
    private void CreateHeader(ref Table tbl)
    {
        TableRow row;
        TableCell cell;
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("Css", "tbl1_trHeader");

        row = new TableRow();

        cell = new TableCell();
        cell.Width = Unit.Percentage(2);
        AddCellTextToRow(row, cell, "STT", msg);

        cell = new TableCell();
        cell.Width = Unit.Percentage(15);
        AddCellTextToRow(row, cell, "Người ký duyệt", msg);

        cell = new TableCell();
        cell.Width = Unit.Percentage(10);
        AddCellTextToRow(row, cell, "Ngày ký duyệt", msg);

        cell = new TableCell();
        cell.Width = Unit.Percentage(45);
        AddCellTextToRow(row, cell, "Ghi chú", msg);

        cell = new TableCell();
        cell.Width = Unit.Percentage(10);
        AddCellTextToRow(row, cell, "Tình trạng", msg);

        tbl.Rows.Add(row);


    } 
    #endregion


    private string AddBasket()
    {
        object ArrPD = (object)Request.QueryString["ArrPD"];
        string[] Arr = ArrPD.ToString().Split(',');
        ArrayList arrOPd = new ArrayList();
        for (int i = 0; i < Arr.Length; i++)
        {
            arrOPd.Add(Arr[i].ToString());
        }
        Session["arrOPd"] = arrOPd;
        return "ok";
    }
    private string OrderAppBasket()
    {
        string sExceptPDR = Request.QueryString["sExceptPDR"];
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("PdName", Uri.UnescapeDataString(Request.QueryString["txtTenSP"].Trim()));
        msg.CreateFirstNode("CatID", Request.QueryString["ddlTheLoai"]);
        msg.CreateFirstNode("TopicID", Request.QueryString["ddlChuDe"]);
        msg.CreateFirstNode("KindNo", Request.QueryString["ddlType"]);
        msg.CreateFirstNode("ExceptPD", sExceptPDR);
        clsWebShop cls = new clsWebShop();
        DataTable dt = null;
        dt = cls.Get_ExceptProductByCondition(msg.GetXmlStr).Tables[0];
        return CreateJsonParameters(dt);

    }
    private string LoadCatalogueByTopic()
    {
        clsWebShop cls = new clsWebShop();
        DataTable dt = null;
        dt = cls.Get_CatalogueByTopicIDNoneProc(Request.QueryString["TopicID"]).Tables[0];
        return CreateJsonParameters(dt);

    }


    #region Common Function

    public string CreateJsonParameters(DataTable dt)
    {
        /* /****************************************************************************
         * Without goingin to the depth of the functioning
         * of this method, i will try to give an overview
         * As soon as this method gets a DataTable it starts to convert it into JSON String,
         * it takes each row and in each row it grabs the cell name and its data.
         * This kind of JSON is very usefull when developer have to have Column name of the .
         * Values Can be Access on clien in this way. OBJ.HEAD[0].<ColumnName>
         * NOTE: One negative point. by this method user
         * will not be able to call any cell by its index.
         * *************************************************************************/

        StringBuilder JsonString = new StringBuilder();

        //Exception Handling
        if (dt != null && dt.Rows.Count > 0)
        {
            JsonString.Append("{ ");
            JsonString.Append("\"Table\":[ ");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                JsonString.Append("{ ");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j < dt.Columns.Count - 1)
                    {
                        JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() +
                              "\":" + "\"" +
                              dt.Rows[i][j].ToString() + "\",");
                    }
                    else if (j == dt.Columns.Count - 1)
                    {
                        JsonString.Append("\"" +
                           dt.Columns[j].ColumnName.ToString() + "\":" +
                           "\"" + dt.Rows[i][j].ToString() + "\"");
                    }
                }

                /*end Of String*/
                if (i == dt.Rows.Count - 1)
                {
                    JsonString.Append("} ");
                }
                else
                {
                    JsonString.Append("}, ");
                }
            }

            JsonString.Append("]}");
            return JsonString.ToString();
        }
        else
        {
            return null;
        }
    }
    private void AddCellTextToRow(TableRow row, TableCell cell, string Text, PccMsg Msg)
    {
        if (Msg.Query("Css") != "") cell.CssClass = Msg.Query("Css");
        cell.Text = Text;
        cell.BorderWidth = Unit.Pixel(1);
        row.Cells.Add(cell);
    }
    private void AddCellHTMLToRow(TableRow row, TableCell cell, string Text, PccMsg Msg)
    {
        Text = Server.HtmlDecode(Text);
        cell.Text = Text;
        cell.BorderWidth = Unit.Pixel(1);
        row.Cells.Add(cell);
    }

    public static string _GetControlRenderString(Control ctrl)
    {
        string ret = "";
        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
        try
        {
            HtmlForm frm = new HtmlForm();
            frm.Controls.Add(ctrl);
            ctrl.RenderControl(htmlWriter);
            ret = stringWriter.ToString().Replace("\n", "").Replace("\t", "").Replace("\r", "");
        }
        catch (Exception e)
        {
            ret = e.Message;
        }
        return ret;
    }
    #endregion
}
